import 'package:demo/app/widgets/dialog_key_value.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../../../model/area_model.dart';
import '../../../../../model/constant_model.dart';
import '../../../../../model/key_value_model.dart';
import '../../../../../model/person_model.dart';
import '../../../../../model/province_model.dart';
import '../../../../../net/api_provider.dart';
import '../base_info_controller.dart';

class Tab1Controller extends GetxController {

  ApiProvider apiProvider = Get.find();
  final FocusNode focusNode = FocusNode();
  void hintKeyboard(){
    focusNode.unfocus(); // 触发焦点变化，键盘收回
  }

  @override
  void onReady() {
    super.onReady();
    getConstant(isFirst: true);
    getProvinceCity();
  }

  Map<String, dynamic>? eduList; /// 学历
  Rx<KeyValue> selectEducation = KeyValue(0,'').obs; /// 选择的学历
  Map<String, dynamic>? marriageList; /// 婚姻
  Rx<KeyValue> selectMarriage = KeyValue(0,'').obs; /// 选择的婚姻
  Map<String, dynamic>? provinceList; /// 省份
  Map<String, dynamic>? cityList; /// 城市
  var selectProvince = KeyValue('',''); /// 选择的省份
  var selectCity = KeyValue('',''); /// 选择的市
  Rx<KeyValue> selectArea = KeyValue(0,'').obs; /// 选择的县
  TextEditingController addressController = TextEditingController(); /// 地址
  TextEditingController emailController = TextEditingController(); /// 邮箱
  Map<String, dynamic>? liveHouseList; /// 住房类型
  Rx<KeyValue> selectLiveHouse = KeyValue(0,'').obs; /// 选择的住房类型
  Map<String, dynamic>? carList; /// 车
  Rx<KeyValue> selectCar = KeyValue(0,'').obs; /// 选择的住车
  Map<String, dynamic>? socialList; /// 社保
  Rx<KeyValue> selectSocial = KeyValue(0,'').obs; /// 选择的社保缴纳
  Map<String, dynamic>? insuranceList; /// 保单
  Rx<KeyValue> selectInsurance = KeyValue(0,'').obs; /// 选择的保单信息
  Map<String, dynamic>? zmScoreList; /// 芝麻分
  Rx<KeyValue> selectZmScore = KeyValue('','').obs; /// 选择的芝麻分 这个key是String
  Map<String, dynamic>? accumulationList; /// 公积金
  Rx<KeyValue> selectAccumulation = KeyValue(0,'').obs; /// 选择的公积金

  /// 获取配置的列表
  void getConstant({bool isFirst = false}) async{
    var result = await apiProvider.getData({}, ApiProvider.constant);
    if(result.code == 200){
      var constant = Constant.fromJson(result.data);
      eduList = constant.eduList;
      marriageList = constant.marriageList;
      liveHouseList = constant.liveHouseList;
      carList = constant.carList;
      socialList = constant.socialList;
      insuranceList = constant.insuranceList;
      zmScoreList = constant.zmScoreList;
      accumulationList = constant.accumulationList;
      if(isFirst){
        getPersonDetail();
      }
    }
  }

  /// 获取省份、城市
  void getProvinceCity() async{
    var result = await apiProvider.getData({}, ApiProvider.province);
    if(result.code == 200){
      var province = Province.fromJson(result.data);
      provinceList = province.provinceList;
      cityList = province.cityList;
    }
  }

  /// 获取个人信息
  void getPersonDetail() async {
    var result = await apiProvider.getData({}, ApiProvider.person_detail);
    if(result.code == 200){
      var person = Person.fromJson(result.data);
      if(eduList != null){
        for(var entry in eduList!.entries) {
          if (entry.key == '${person.educationId}'){
            selectEducation.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      if(marriageList != null){
        for(var entry in marriageList!.entries) {
          if (entry.key == '${person.marryId}'){
            selectMarriage.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      if (person.provCode.isNotEmpty && person.ipProvince.isNotEmpty){
        selectProvince = KeyValue(person.provCode,person.ipProvince); /// 选择的省份
      }
      if (person.cityCode.isNotEmpty && person.ipCity.isNotEmpty){
        selectCity = KeyValue(person.cityCode,person.ipCity); /// 选择的市
      }
      if (person.areaCode.isNotEmpty && person.area.isNotEmpty){
        selectArea.value = KeyValue(person.areaCode,person.area); /// 选择的县
      }
      addressController.text = person.address;
      if(liveHouseList != null){
        for(var entry in liveHouseList!.entries) {
          if (entry.key == '${person.houseId}'){
            selectLiveHouse.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      emailController.text = person.email;

      if(accumulationList != null){
        for(var entry in accumulationList!.entries) {
          if (entry.key == '${person.accumulationId}'){
            selectAccumulation.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      if(carList != null){
        for(var entry in carList!.entries) {
          if (entry.key == '${person.carId}'){
            selectCar.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      if(insuranceList != null){
        for(var entry in insuranceList!.entries) {
          if (entry.key == '${person.insuranceId}'){
            selectInsurance.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      if(socialList != null){
        for(var entry in socialList!.entries) {
          if (entry.key == '${person.socialId}'){
            selectSocial.value = KeyValue(int.tryParse(entry.key) ?? 0,entry.value);
          }
        }
      }
      if(zmScoreList != null){
        for(var entry in zmScoreList!.entries) {
          if (entry.key == person.zmScore){
            selectZmScore.value = KeyValue(entry.key,entry.value);
          }
        }
      }
    }
  }

  /// 选择学历
  void chooseEducation() {
    hintKeyboard();
    if(eduList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(eduList!, (code,value){
        selectEducation.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }
  
  /// 选择婚姻
  void chooseMarital() {
    hintKeyboard();
    if(marriageList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(marriageList!, (code,value){
        selectMarriage.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 选择省份
  void chooseProvince(){
    hintKeyboard();
    if(provinceList == null || cityList == null){
      getProvinceCity();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(provinceList, (proCode,proValue){
        var s = proCode.substring(0,2);
        Map<String, dynamic> list = {};
        cityList!.forEach((key, value) {
          if(key.startsWith(s)){
            list[key] = value;
          }
        });

        Future.delayed(const Duration(milliseconds: 100), () {
          Get.bottomSheet(
            DialogKeyValue(list, (cityCode,cityValue) async {
              var result = await apiProvider.getData({'code':cityCode}, ApiProvider.area);
              if(result.code == 200){
                var area = Area.fromJson(result.data);
                Get.bottomSheet(
                  DialogKeyValue(area.area_list, (areaCode,areaValue) {
                    selectProvince = KeyValue(proCode, proValue);
                    selectCity = KeyValue(cityCode,cityValue); // 选择的市
                    selectArea.value = KeyValue(areaCode,areaValue); // 选择的县
                  }),
                );
              }
            }),
          );
        });
      }),
    );
  }

  /// 选择住房类型
  void chooseLiveHouse() {
    hintKeyboard();
    if(liveHouseList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(liveHouseList, (code,value){
        selectLiveHouse.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 选择车辆信息
  void chooseCar() {
    hintKeyboard();
    if(carList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(carList, (code,value){
        selectCar.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }
  /// 选择社保缴纳
  void chooseSocial() {
    hintKeyboard();
    if(socialList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(socialList, (code,value){
        selectSocial.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }
  /// 选择保单信息
  void chooseInsurance() {
    hintKeyboard();
    if(insuranceList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(insuranceList, (code,value){
        selectInsurance.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }
  /// 选择芝麻分
  void chooseZmScore() {
    hintKeyboard();
    if(zmScoreList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(zmScoreList, (code,value){
        selectZmScore.value = KeyValue(code,value);
      }),
    );
  }
  /// 选择公积金
  void chooseAccumulation() {
    hintKeyboard();
    if(accumulationList == null){
      getConstant();
      return;
    }

    Get.bottomSheet(
      DialogKeyValue(accumulationList, (code,value){
        selectAccumulation.value = KeyValue(int.tryParse(code) ?? 0,value);
      }),
    );
  }

  /// 提交
  void submit() async{
    if (selectEducation.value.key == 0 || '${selectEducation.value.value}'.isEmpty){
      EasyLoading.showToast('请选择学历');
      return;
    }
    if (selectMarriage.value.key == 0 || '${selectMarriage.value.value}'.isEmpty){
      EasyLoading.showToast('请选择婚姻情况');
      return;
    }
    if (selectProvince.key.isEmpty || selectProvince.value.isEmpty || selectCity.key.isEmpty || selectCity.value.isEmpty || selectArea.value.key.isEmpty || selectArea.value.value.isEmpty){
      EasyLoading.showToast('请选择居住城市');
      return;
    }
    if (addressController.text.isEmpty || addressController.text.length < 4){
      EasyLoading.showToast('请填写正确的地址');
      return;
    }
    if (selectLiveHouse.value.key == 0 || '${selectLiveHouse.value.value}'.isEmpty){
      EasyLoading.showToast('请选择住房类型');
      return;
    }
    if (selectCar.value.key == 0 || '${selectCar.value.value}'.isEmpty){
      EasyLoading.showToast('请选择车辆信息');
      return;
    }
    if (selectSocial.value.key == 0 || '${selectSocial.value.value}'.isEmpty){
      EasyLoading.showToast('请选择社保信息');
      return;
    }
    if (selectInsurance.value.key == 0 || '${selectInsurance.value.value}'.isEmpty){
      EasyLoading.showToast('请选择保单信息');
      return;
    }
    if (selectZmScore.value.key == '-1' || '${selectZmScore.value.value}'.isEmpty){
      EasyLoading.showToast('请选择芝麻分');
      return;
    }
    if (selectAccumulation.value.key == 0 || '${selectAccumulation.value.value}'.isEmpty){
      EasyLoading.showToast('请选择公积金');
      return;
    }
    if (emailController.text.isEmpty || !emailController.text.isEmail){
      EasyLoading.showToast('请填写正确的邮箱');
      return;
    }

    Map<String, dynamic> obj = {
      'education_id' : selectEducation.value.key, // 学历
      'marry_id' : selectMarriage.value.key, // 婚姻状况
      'ip_province' : selectProvince.value,
      'prov_code' : selectProvince.key,
      'ip_city' : selectCity.value,
      'city_code' : selectCity.key,
      'area_code' : selectArea.value.key,
      'area' : selectArea.value.value,
      'address' : addressController.text, // 详细地址
      'house_id' : selectLiveHouse.value.key, // 住房类型
      'car_id' : selectCar.value.key, //
      'social_id' : selectSocial.value.key, //
      'insurance_id' : selectInsurance.value.key, //
      'zm_score' : selectZmScore.value.key, //
      'accumulation_id' : selectAccumulation.value.key, //
      'email' : emailController.text // 邮箱
    };
    var result = await apiProvider.getData(obj, ApiProvider.person_updated);
    if(result.code == 200){
      BaseInfoController c = Get.find();
      c.setCurrentIndex(1);
    }
  }
}
